<?php


namespace app\api\controller;


use app\admin\model\System\SysPayModel;
use app\api\model\Collage\CollageModel;
use app\api\model\Goods\GoodsModel;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\School\SchoolWalletModel;
use app\api\model\User\UserModel;
use app\api\model\User\UserWalletModel;
use app\Utils\StrUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\facade\Log;
use Yansongda\Pay\Pay;

class WxNotify extends BaseController
{

    protected $config;
    protected $extend_json;

    public function __construct()
    {
        $wx = SysPayModel::getSysPayWhere([['id', '=', 3]]);
        $this->extend_json = json_decode($wx['extend_json'], true);
        $this->config = [
            'appid' => $this->extend_json['app_id'], // APPID
            'mch_id' => $this->extend_json['mch_id'],
            'key' => $this->extend_json['key'],
            'cert_client' => 'http://systudyad.shawyo.com/payment/weixin/cert/apiclient_cert.pem', // optional，退款等情况时用到
            'cert_key' => 'http://systudyad.shawyo.com/payment/weixin/cert/apiclient_key.pem',// optional，退款等情况时用到

        ];
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * 微信回调
     */
    public function notify()
    {
        $pay = Pay::wechat($this->config);
        try {
            $data = $pay->verify(); //验签
            $result = $this->payLogics($data->all());
            if ($result) {
                return $pay->success();
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }
        return $pay->success();
    }

    /**
     * @param array $data
     * @return bool
     */
    protected function payLogics(array $data)
    {
        if (!($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS')) return false;

        $order = OrderModel::getOrderWhere([['out_trade_no', '=', $data['out_trade_no']]]);

        if (!$order) return false;

        if ($order['status'] != 0) return true;

        $goods = OrderGoodsModel::getOrderGoodsListWhereMore([['order_id', '=', $order['id']]]);

        Db::startTrans();
        try {
            switch ($order['type']) {
                case 1:  //商品
                    $this->goods_notify($goods, $order['id'], $order);
                    break;
                case 2:  //会员
                    $this->member_notify($goods, $order);
                    break;
                case 3: //课程
                    $this->course_notify($goods, $order['id'], $order);
                    break;
            }
            $save = [
                'trade_no' => $data['transaction_id'],
                'price' => $data['total_fee'] / 100,
                'status' => 1,
                'up_time' => date('Y-m-d H:i:s', time())
            ];
            OrderModel::updateOrderWhere(['id' => $order['id']], $save);
            Db::commit();
            return true;
        } catch (Exception $exception) {
            Db::rollback();
            return false;
        }

    }

    /**
     * 商品信息回调
     */
    protected function goods_notify($goods, int $order_id, $order)
    {

        #购买商品
        //执行增加销量减库存操作
        foreach ($goods as $item) {
            $flag = GoodsModel::goodsInOut($item['goods_id'], $item['number']);
            if (!$flag) {
                Db::rollback();
                return false;
            }
        }
        if (!empty($order['is_group'])) {

            if (!empty($order['temp_collage_id'])) {
                //检查团是否已满
                $collage = CollageModel::getCollageWhere(['id' => $order['temp_collage_id']]);
                if (!empty($collage)) {
                    if (!empty($collage['status'])) {
                        //团满开新团
                        $collage_sn = StrUtil::i()->getOrderSn(2);
                        $time = date("Y-m-d H:i:s", time());
                        $end_time = date('Y-m-d H:i:s', strtotime($time) + 86400);
                        $goodsInfo = GoodsModel::getGoodsWhere(['id' => $goods[0]['goods_id']]);
                        $collage_data = [
                            'collage_sn' => $collage_sn,
                            'uid' => $order['uid'],
                            'goods_id' => $goodsInfo['id'],
                            'collage_count' => $goodsInfo['group_num'],
                            'now_count' => 1,
                            'up_time' => $time,
                            'add_time' => $time,
                            'mer_id' => $goodsInfo['mer_id'],
                            'start_time' => $time,
                            'end_time' => $end_time,
                            'goods_info' => json_encode($goodsInfo),
                        ];

                        if (1 >= $goodsInfo['group_num']) {
                            $collage_data['status'] = 1;
                        } else {
                            $collage_data['status'] = 0;
                        }
                        $collage_id = CollageModel::addCollage($collage_data);
                        if (!empty($collage_id)) {
                            $order_save = [
                                'collage_id' => $collage_id
                            ];
                            OrderModel::updateOrderWhere(['id' => $order['id']], $order_save);
                        } else {
                            Log::record('拼团失败' . $order_id . '创建拼团失败');
                        }
                    } else {
                        //加入团
                        $now_count = $collage['now_count'] + 1;
                        $collage_save = [
                            'now_count' => $now_count,
                            'up_time' => date("Y-m-d H:i:s", time()),
                        ];
                        if ($now_count >= $collage['collage_count']) {
                            $collage_save['status'] = 1;
                        }
                        CollageModel::updateCollageData(['id' => $collage['id']], $collage_save);
                        $order_save = [
                            'collage_id' => $order['temp_collage_id']
                        ];
                        OrderModel::updateOrderWhere(['id' => $order['id']], $order_save);
                    }
                } else {
                    Log::record('拼团失败' . $order_id . '团不存在');
                    return false;
                }
            } else {
                //新增团
                $collage_sn = StrUtil::i()->getOrderSn(2);
                $time = date("Y-m-d H:i:s", time());
                $end_time = date('Y-m-d H:i:s', strtotime($time) + 86400);
                $goodsInfo = GoodsModel::getGoodsWhere(['id' => $goods[0]['goods_id']]);
                $collage_data = [
                    'collage_sn' => $collage_sn,
                    'uid' => $order['uid'],
                    'goods_id' => $goodsInfo['id'],
                    'collage_count' => $goodsInfo['group_num'],
                    'now_count' => 1,
                    'up_time' => $time,
                    'add_time' => $time,
                    'mer_id' => $goodsInfo['mer_id'],
                    'start_time' => $time,
                    'end_time' => $end_time,
                    'goods_info' => json_encode($goodsInfo),
                ];

                if (1 >= $goodsInfo['group_num']) {
                    $collage_data['status'] = 1;
                } else {
                    $collage_data['status'] = 0;
                }
                $collage_id = CollageModel::addCollage($collage_data);
                if (!empty($collage_id)) {
                    $order_save = [
                        'collage_id' => $collage_id
                    ];
                    OrderModel::updateOrderWhere(['id' => $order['id']], $order_save);
                } else {
                    Log::record('拼团失败' . $order_id . '创建拼团失败');
                    return false;
                }
            }
        }
    }

    /**
     * @param $goods
     * @param $order
     * @throws \think\db\exception\DbException
     * 会员处理
     */
    protected function member_notify($goods, $order)
    {
        $goodsInfo = json_decode($goods[0]['goods_info'], true);
        #购买会员
        $user = UserModel::getUserWhere(['id' => $order['uid']], 'id,level_id,is_level_type,end_time,parent_uid,parent_reward');

        //------开始发放佣金--------
        if (!empty($order)) {
            $order_goods = OrderGoodsModel::getOrderGoodsListWhereMore(['order_id' => $order['id']]);
            if (!empty($order_goods)) {
                foreach ($order_goods as $order_good) {
                    if ($order_good['is_sales'] == 1 || $order_good['is_sales'] == 2) {
                        if (!empty($order_good['agnet_uid1']) && $order_good['agent_amount1'] > 0 && $order_good['agent_status1'] == 0) {
                            UserWalletModel::walletIn($order_good['agnet_uid1'], $order_good['agent_amount1'], StrUtil::BILL_USE_TYPE['VIP_COMMISSION'], "购买会员佣金", $order_good['id']);
                            OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status1' => 1]);
                            Db::name('user_wallet')->where('uid', $order_good['agnet_uid1'])->inc('reward', $order_good['agent_amount1'])->update();
                        }
                        if (!empty($order_good['agnet_uid2']) && $order_good['agent_amount2'] > 0 && $order_good['agent_status2'] == 0) {
                            UserWalletModel::walletIn($order_good['agnet_uid2'], $order_good['agent_amount2'], StrUtil::BILL_USE_TYPE['VIP_COMMISSION'], "购买会员佣金", $order_good['id']);
                            OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status2' => 1]);
                            Db::name('user_wallet')->where('uid', $order_good['agnet_uid2'])->inc('reward', $order_good['agent_amount2'])->update();
                        }
                        if (!empty($order_good['agnet_uid3']) && $order_good['agent_amount3'] > 0 && $order_good['agent_status3'] == 0) {
                            UserWalletModel::walletIn($order_good['agnet_uid3'], $order_good['agent_amount3'], StrUtil::BILL_USE_TYPE['VIP_COMMISSION'], "购买会员佣金", $order_good['id']);
                            OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status3' => 1]);
                            Db::name('user_wallet')->where('uid', $order_good['agnet_uid3'])->inc('reward', $order_good['agent_amount3'])->update();
                        }
                    }
                }
            }
        }
        //------结束发放佣金--------

        if ($goodsInfo['type'] == 1) {
            //永久
            $data_user = [
                'level_id' => $goodsInfo['id'],
                'is_level_type' => 1
            ];
        } else {
            if ($user['end_time']) {
                if (strtotime($user['end_time']) > time()) {
                    $time = strtotime($user['end_time']) + ((int)$goodsInfo['day'] * 3600 * 24);
                } else {
                    $time = time() + (((int)$goodsInfo['day'] * 3600 * 24));
                }
            } else {
                $time = time() + (((int)$goodsInfo['day'] * 3600 * 24));
            }
            if ($user['level_id'] < $goodsInfo['id']) {
                $data_user = [
                    'level_id' => $user['level_id'],
                    'is_level_type' => 0,
                    'end_time' => date('Y-m-d H:i:s', $time)
                ];
            } else {
                $data_user = [
                    'level_id' => $goodsInfo['id'],
                    'is_level_type' => 0,
                    'end_time' => date('Y-m-d H:i:s', $time)
                ];
            }
        }
        $res_user = UserModel::updateUserWhere(['id' => $user['id']], $data_user);
        if ($res_user) {
            return true;
        }
        return false;
    }

    /**
     * @param $goods
     * @param $order_id
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function course_notify($goods, $order_id, $order)
    {
        $goods = $goods[0];
        #购买课程
        #增加课程销量
        $result = Db::name('course')->where('id', $goods['goods_id'])->inc('sales', $order['pay_num'])->update();
        if (!$result) return false;
        if ($goods['mer_id']) {
            $goods['ratio'] = $goods['ratio'] > 1 ? 1 : $goods['ratio'];
            #增加学校钱包余额
            $result = SchoolWalletModel::walletIn($goods['mer_id'], round($goods['total_price'] * (1 - $goods['ratio']), 2), StrUtil::MER_BILL_USE_TYPE['SELL_COURSE'], '售卖课程');
            if (!$result) return false;
        }
        if ($order['is_group']) {
            $course = Db::name('course')->where('id', $goods['goods_id'])->find();
            self::course_collage($order, $course);
        }

        //------开始发放佣金--------
        if (!empty($order)) {
            $order_goods = OrderGoodsModel::getOrderGoodsListWhereMore(['order_id' => $order['id']]);
            if (!empty($order_goods)) {
                foreach ($order_goods as $order_good) {
                    if ($order_good['is_sales'] == 1 || $order_good['is_sales'] == 2) {
                        if (!empty($order_good['agnet_uid1']) && $order_good['agent_amount1'] > 0 && $order_good['agent_status1'] == 0) {
                            UserWalletModel::walletIn($order_good['agnet_uid1'], $order_good['agent_amount1'], StrUtil::BILL_USE_TYPE['COURSE_COMMISSION'], "课程佣金", $order_good['id']);
                            OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status1' => 1]);
                            Db::name('user_wallet')->where('uid', $order_good['agnet_uid1'])->inc('reward', $order_good['agent_amount1'])->update();
                        }
                        if (!empty($order_good['agnet_uid2']) && $order_good['agent_amount2'] > 0 && $order_good['agent_status2'] == 0) {
                            UserWalletModel::walletIn($order_good['agnet_uid2'], $order_good['agent_amount2'], StrUtil::BILL_USE_TYPE['COURSE_COMMISSION'], "课程佣金", $order_good['id']);
                            OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status2' => 1]);
                            Db::name('user_wallet')->where('uid', $order_good['agnet_uid2'])->inc('reward', $order_good['agent_amount2'])->update();
                        }
                        if (!empty($order_good['agnet_uid3']) && $order_good['agent_amount3'] > 0 && $order_good['agent_status3'] == 0) {
                            UserWalletModel::walletIn($order_good['agnet_uid3'], $order_good['agent_amount3'], StrUtil::BILL_USE_TYPE['COURSE_COMMISSION'], "课程佣金", $order_good['id']);
                            OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status3' => 1]);
                            Db::name('user_wallet')->where('uid', $order_good['agnet_uid3'])->inc('reward', $order_good['agent_amount3'])->update();
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * @param $order
     * @param $course
     * 记录拼团信息
     */
    protected function course_collage($order, $course)
    {

        $data = [
            'collage_sn' => $order['order_sn'],
            'course_id' => $course['id'],
            'user_id' => $order['uid'],
            'up_time' => date('Y-m-d H:i:s'),
            'add_time' => date('Y-m-d H:i:s'),
            'mer_id' => $order['mer_id'],
            'start_time' => $course['start_time'],
            'end_time' => $course['end_time'],
            'course_info' => $course
        ];
        Db::name('course_collage')->insert($data);
        return true;
    }


}